/**
 * @file service_factory.h
 * @brief 服务工厂模板 - 简化依赖注入和服务注册
 * @version 2.0
 */
#pragma once

#include "infrastructure/di/servicecontainer.h"
#include "kernel/interfaces/ILogger.h"
#include <functional>
#include <memory>
#include <type_traits>

namespace bootstrap {
namespace factories {

using namespace infrastructure;

/**
 * @brief 服务配置结构
 */
struct ServiceConfig {
    Lifecycle lifecycle = Lifecycle::Singleton;
    bool required = true;
    bool autoInitialize = true;
    std::string description = "";
};

/**
 * @brief 服务注册工厂模板 - 大幅简化服务注册代码
 */
template<typename TInterface, typename TImplementation>
class ServiceFactory {
public:
    /**
     * @brief 创建简单服务工厂（只需要logger依赖）
     */
    static auto createSimple() {
        return [](ServiceContainer& container) -> std::shared_ptr<TImplementation> {
            auto logger = container.resolve<kernel::ILogger>();
            if (!logger) {
                throw std::runtime_error("无法解析日志记录器服务");
            }
            
            return std::make_shared<TImplementation>(logger);
        };
    }
    
    /**
     * @brief 创建单依赖服务工厂
     */
    template<typename TDependency>
    static auto createWithDependency() {
        return [](ServiceContainer& container) -> std::shared_ptr<TImplementation> {
            // 自动解析依赖
            auto dependency = container.resolve<TDependency>();
            if (!dependency) {
                throw std::runtime_error("无法解析必需的依赖服务");
            }
            
            auto logger = container.resolve<kernel::ILogger>();
            if (!logger) {
                throw std::runtime_error("无法解析日志记录器服务");
            }
            
            return std::make_shared<TImplementation>(dependency, logger);
        };
    }
    
    /**
     * @brief 创建多依赖服务工厂  
     */
    template<typename... TDependencies>
    static auto createWithDependencies() {
        return [](ServiceContainer& container) -> std::shared_ptr<TImplementation> {
            // 使用折叠表达式解析所有依赖
            auto dependencies = std::make_tuple(
                resolveDependency<TDependencies>(container)...
            );
            
            auto logger = container.resolve<kernel::ILogger>();
            if (!logger) {
                throw std::runtime_error("无法解析日志记录器服务");
            }
            
            // 使用tuple构造服务实例
            return std::apply([&logger](auto&&... deps) {
                return std::make_shared<TImplementation>(
                    std::forward<decltype(deps)>(deps)..., logger);
            }, dependencies);
        };
    }
    
    /**
     * @brief 创建自定义工厂
     */
    template<typename FactoryFunc>
    static auto createCustom(FactoryFunc&& factory) {
        return std::forward<FactoryFunc>(factory);
    }

private:
    template<typename T>
    static std::shared_ptr<T> resolveDependency(ServiceContainer& container) {
        auto dependency = container.resolve<T>();
        if (!dependency) {
            throw std::runtime_error("无法解析依赖服务: " + std::string(typeid(T).name()));
        }
        return dependency;
    }
};

/**
 * @brief 服务注册构建器 - 链式API设计
 */
template<typename TInterface, typename TImplementation>
class ServiceRegistrationBuilder {
private:
    ServiceConfig m_config;
    std::function<std::shared_ptr<TImplementation>(ServiceContainer&)> m_factory;

public:
    ServiceRegistrationBuilder() = default;
    
    /**
     * @brief 设置生命周期
     */
    ServiceRegistrationBuilder& withLifecycle(Lifecycle lifecycle) {
        m_config.lifecycle = lifecycle;
        return *this;
    }
    
    /**
     * @brief 设置是否必需
     */
    ServiceRegistrationBuilder& asRequired(bool required = true) {
        m_config.required = required;
        return *this;
    }
    
    /**
     * @brief 设置是否自动初始化
     */
    ServiceRegistrationBuilder& withAutoInitialize(bool autoInit = true) {
        m_config.autoInitialize = autoInit;
        return *this;
    }
    
    /**
     * @brief 设置描述
     */
    ServiceRegistrationBuilder& withDescription(const std::string& desc) {
        m_config.description = desc;
        return *this;
    }
    
    /**
     * @brief 使用简单工厂（只需要logger）
     */
    ServiceRegistrationBuilder& useSimpleFactory() {
        m_factory = ServiceFactory<TInterface, TImplementation>::createSimple();
        return *this;
    }
    
    /**
     * @brief 使用单依赖工厂
     */
    template<typename TDependency>
    ServiceRegistrationBuilder& useDependency() {
        m_factory = ServiceFactory<TInterface, TImplementation>::template createWithDependency<TDependency>();
        return *this;
    }
    
    /**
     * @brief 使用多依赖工厂
     */
    template<typename... TDependencies>
    ServiceRegistrationBuilder& useDependencies() {
        m_factory = ServiceFactory<TInterface, TImplementation>::template createWithDependencies<TDependencies...>();
        return *this;
    }
    
    /**
     * @brief 使用自定义工厂
     */
    template<typename FactoryFunc>
    ServiceRegistrationBuilder& useCustomFactory(FactoryFunc&& factory) {
        m_factory = std::forward<FactoryFunc>(factory);
        return *this;
    }
    
    /**
     * @brief 注册到容器
     */
    void registerTo(ServiceContainer& container) {
        if (!m_factory) {
            throw std::runtime_error("服务工厂未设置");
        }
        
        container.registerFactory<TInterface, TImplementation>(
            m_config.lifecycle, m_factory);
    }
    
    /**
     * @brief 获取配置信息
     */
    const ServiceConfig& getConfig() const { 
        return m_config; 
    }
};

/**
 * @brief 便捷的注册函数
 */
template<typename TInterface, typename TImplementation>
ServiceRegistrationBuilder<TInterface, TImplementation> registerService() {
    return ServiceRegistrationBuilder<TInterface, TImplementation>();
}

} // namespace factories
} // namespace bootstrap